<template>
  <div class="score-statistics">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>统计报表</el-breadcrumb-item>
      <el-breadcrumb-item>成绩统计</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 成绩统计概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #409eff;">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ overviewData.totalResults || 0 }}</div>
              <div class="stat-label">总成绩记录数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #f56c6c;">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ overviewData.recordBreakingCount || 0 }}</div>
              <div class="stat-label">破纪录次数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #67c23a;">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ overviewData.participantCount || 0 }}</div>
              <div class="stat-label">参与运动员数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #e6a23c;">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ overviewData.todayResults || 0 }}</div>
              <div class="stat-label">今日新增成绩</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选和操作区域 -->
    <el-card class="filter-card">
      <div class="filter-header">
        <div class="left-actions">
          <el-button type="primary" icon="Refresh" @click="handleRefresh">
            刷新数据
          </el-button>
          <el-button type="success" icon="Download" @click="handleExport">
            导出报表
          </el-button>
          <el-button type="info" icon="Document" @click="handleGenerateReport">
            生成分析报告
          </el-button>
        </div>
        <div class="right-filters">
          <el-select
            v-model="filterForm.projectId"
            placeholder="选择项目"
            clearable
            style="width: 180px; margin-right: 10px;"
            @change="handleProjectChange"
          >
            <el-option
              v-for="project in projectOptions"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
          <el-select
            v-model="filterForm.projectType"
            placeholder="项目类型"
            clearable
            style="width: 120px; margin-right: 10px;"
            @change="handleFilterChange"
          >
            <el-option label="个人项目" value="personal" />
            <el-option label="团体项目" value="team" />
          </el-select>
          <el-select
            v-model="filterForm.timeRange"
            placeholder="时间范围"
            style="width: 130px;"
            @change="handleTimeRangeChange"
          >
            <el-option label="今日" value="today" />
            <el-option label="最近3天" value="3days" />
            <el-option label="最近7天" value="7days" />
            <el-option label="最近30天" value="30days" />
          </el-select>
        </div>
      </div>
    </el-card>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 成绩分布图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>成绩分布分析</span>
              <el-select v-model="distributionChartType" size="small" style="width: 100px;">
                <el-option label="直方图" value="histogram" />
                <el-option label="箱线图" value="box" />
              </el-select>
            </div>
          </template>
          <div ref="distributionChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 破纪录统计 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>破纪录统计分析</span>
              <el-radio-group v-model="recordChartType" size="small">
                <el-radio-button label="time">按时间</el-radio-button>
                <el-radio-button label="project">按项目</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="recordChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 成绩趋势和项目对比 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 成绩趋势图 -->
      <el-col :span="14">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>成绩趋势分析</span>
              <el-select v-model="trendMetricType" size="small" style="width: 120px;">
                <el-option label="平均成绩" value="average" />
                <el-option label="最高成绩" value="best" />
                <el-option label="进步幅度" value="improvement" />
              </el-select>
            </div>
          </template>
          <div ref="trendChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 成绩排行榜 -->
      <el-col :span="10">
        <el-card class="ranking-card">
          <template #header>
            <div class="card-header">
              <span>成绩排行榜</span>
              <el-select v-model="rankingType" size="small" style="width: 100px;">
                <el-option label="总榜" value="total" />
                <el-option label="项目榜" value="project" />
              </el-select>
            </div>
          </template>
          <div class="ranking-content">
            <div class="ranking-list">
              <div
                v-for="(item, index) in rankingData"
                :key="item.id"
                class="ranking-item"
                :class="{ 'top-three': index < 3 }"
                @mouseenter="handleRankingHover(item, index)"
                @mouseleave="handleRankingLeave"
              >
                <div class="rank-number" :class="`rank-${index + 1}`">
                  <el-icon v-if="index === 0"><Trophy /></el-icon>
                  <el-icon v-else-if="index === 1"><Medal /></el-icon>
                  <el-icon v-else-if="index === 2"><Medal /></el-icon>
                  <span v-else>{{ index + 1 }}</span>
                </div>
                <div class="rank-info">
                  <div class="rank-name">{{ item.participantName }}</div>
                  <div class="rank-project">{{ item.projectName }}</div>
                </div>
                <div class="rank-score">
                  <div class="score-value">{{ item.score }}</div>
                  <div class="score-unit">{{ item.unit }}</div>
                </div>
                <div class="rank-badge">
                  <el-tag v-if="item.isRecord" type="danger" size="small">破纪录</el-tag>
                  <el-tag v-if="item.isPB" type="success" size="small">PB</el-tag>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>成绩详细数据</span>
          <div class="table-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索运动员、项目或成绩"
              style="width: 200px; margin-right: 10px;"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" />
              </template>
            </el-input>
            <el-button type="primary" icon="Download" @click="exportTableData">
              导出表格
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="tableLoading"
        :data="tableData"
        stripe
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column type="index" label="#" width="60" />
        <el-table-column prop="participantName" label="运动员" min-width="120" />
        <el-table-column prop="studentId" label="学号" width="120" />
        <el-table-column prop="collegeName" label="学院" min-width="120" />
        <el-table-column prop="className" label="班级" min-width="120" />
        <el-table-column prop="projectName" label="项目名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="score" label="成绩" width="100" sortable="custom">
          <template #default="{ row }">
            <span class="score-highlight">{{ row.score }} {{ row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="rank" label="排名" width="80" sortable="custom">
          <template #default="{ row }">
            <el-tag v-if="row.rank <= 3" :type="row.rank === 1 ? 'danger' : row.rank === 2 ? 'warning' : 'info'">
              第{{ row.rank }}名
            </el-tag>
            <span v-else>第{{ row.rank }}名</span>
          </template>
        </el-table-column>
        <el-table-column prop="isRecord" label="是否破纪录" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.isRecord" type="danger" size="small">是</el-tag>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column prop="isPB" label="个人最好" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.isPB" type="success" size="small">是</el-tag>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column prop="recordTime" label="记录时间" width="180" sortable="custom" />
        <el-table-column prop="improvement" label="进步幅度" width="100">
          <template #default="{ row }">
            <span v-if="row.improvement" :class="row.improvement > 0 ? 'improvement-positive' : 'improvement-negative'">
              {{ row.improvement > 0 ? '+' : '' }}{{ row.improvement }}{{ row.unit }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="View"
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 成绩详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="成绩详情"
      width="900px"
    >
      <div class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="运动员">{{ currentDetail.participantName }}</el-descriptions-item>
          <el-descriptions-item label="学号">{{ currentDetail.studentId }}</el-descriptions-item>
          <el-descriptions-item label="学院">{{ currentDetail.collegeName }}</el-descriptions-item>
          <el-descriptions-item label="班级">{{ currentDetail.className }}</el-descriptions-item>
          <el-descriptions-item label="项目名称">{{ currentDetail.projectName }}</el-descriptions-item>
          <el-descriptions-item label="项目类型">
            <el-tag :type="currentDetail.projectType === '个人' ? 'primary' : 'success'">
              {{ currentDetail.projectType }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="成绩">
            <span class="score-detail">{{ currentDetail.score }} {{ currentDetail.unit }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="排名">
            <el-tag v-if="currentDetail.rank <= 3" :type="currentDetail.rank === 1 ? 'danger' : currentDetail.rank === 2 ? 'warning' : 'info'">
              第{{ currentDetail.rank }}名
            </el-tag>
            <span v-else>第{{ currentDetail.rank }}名</span>
          </el-descriptions-item>
          <el-descriptions-item label="是否破纪录">
            <el-tag v-if="currentDetail.isRecord" type="danger">是</el-tag>
            <span v-else>否</span>
          </el-descriptions-item>
          <el-descriptions-item label="个人最好成绩">
            <el-tag v-if="currentDetail.isPB" type="success">是</el-tag>
            <span v-else>否</span>
          </el-descriptions-item>
          <el-descriptions-item label="原纪录">{{ currentDetail.originalRecord || '-' }}</el-descriptions-item>
          <el-descriptions-item label="进步幅度">
            <span v-if="currentDetail.improvement" :class="currentDetail.improvement > 0 ? 'improvement-positive' : 'improvement-negative'">
              {{ currentDetail.improvement > 0 ? '+' : '' }}{{ currentDetail.improvement }}{{ currentDetail.unit }}
            </span>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="记录时间">{{ currentDetail.recordTime }}</el-descriptions-item>
          <el-descriptions-item label="比赛场地">{{ currentDetail.venue || '-' }}</el-descriptions-item>
          <el-descriptions-item label="裁判员">{{ currentDetail.refereeName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="天气状况">{{ currentDetail.weather || '-' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 历史成绩对比 -->
        <div v-if="currentDetail.historyScores && currentDetail.historyScores.length" class="history-section">
          <h4>历史成绩对比</h4>
          <el-table :data="currentDetail.historyScores" size="small" stripe>
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="score" label="成绩" width="100" />
            <el-table-column prop="improvement" label="进步幅度" width="100">
              <template #default="{ row }">
                <span v-if="row.improvement" :class="row.improvement > 0 ? 'improvement-positive' : 'improvement-negative'">
                  {{ row.improvement > 0 ? '+' : '' }}{{ row.improvement }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="competition" label="比赛" show-overflow-tooltip />
          </el-table>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="exportDetailData">导出详情</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 成绩分析对话框 -->
    <el-dialog
      v-model="analysisDialogVisible"
      title="成绩分析报告"
      width="1000px"
    >
      <div class="analysis-content">
        <el-tabs v-model="activeAnalysisTab">
          <el-tab-pane label="总体分析" name="overall">
            <div class="analysis-section">
              <h4>成绩分布统计</h4>
              <div ref="analysisChart1" class="analysis-chart"></div>
            </div>
            <div class="analysis-section">
              <h4>项目对比分析</h4>
              <div ref="analysisChart2" class="analysis-chart"></div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="趋势分析" name="trend">
            <div class="analysis-section">
              <h4>成绩变化趋势</h4>
              <div ref="analysisChart3" class="analysis-chart"></div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="破纪录分析" name="record">
            <div class="analysis-section">
              <h4>破纪录统计</h4>
              <div ref="analysisChart4" class="analysis-chart"></div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="analysisDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="exportAnalysisReport">导出分析报告</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import {
  getScoreOverview,
  getProjectRanking,
  getRecordBreakingStats,
  getScoreDistribution,
  getScoreComparisonChart,
  exportScoreStats,
  getProjectOverview
} from '@/api/statistics'

export default {
  name: 'ScoreStatistics',
  setup() {
    // 响应式数据
    const loading = ref(false)
    const tableLoading = ref(false)
    const overviewData = reactive({
      totalResults: 0,
      recordBreakingCount: 0,
      participantCount: 0,
      todayResults: 0
    })

    // 图表相关
    const distributionChart = ref(null)
    const recordChart = ref(null)
    const trendChart = ref(null)
    let distributionChartInstance = null
    let recordChartInstance = null
    let trendChartInstance = null

    // 图表类型
    const distributionChartType = ref('histogram')
    const recordChartType = ref('time')
    const trendMetricType = ref('average')
    const rankingType = ref('total')

    // 筛选表单
    const filterForm = reactive({
      projectId: null,
      projectType: '',
      timeRange: '7days'
    })

    // 项目选项
    const projectOptions = ref([])

    // 搜索关键词
    const searchKeyword = ref('')

    // 表格数据
    const tableData = ref([])
    const pagination = reactive({
      currentPage: 1,
      pageSize: 20,
      total: 0
    })

    // 排序参数
    const sortParams = reactive({
      prop: '',
      order: ''
    })

    // 排行榜数据
    const rankingData = ref([])

    // 对话框控制
    const detailDialogVisible = ref(false)
    const analysisDialogVisible = ref(false)
    const currentDetail = ref({})
    const activeAnalysisTab = ref('overall')

    // 分析图表
    const analysisChart1 = ref(null)
    const analysisChart2 = ref(null)
    const analysisChart3 = ref(null)
    const analysisChart4 = ref(null)
    let analysisChart1Instance = null
    let analysisChart2Instance = null
    let analysisChart3Instance = null
    let analysisChart4Instance = null

    // 生命周期钩子
    onMounted(() => {
      loadOverviewData()
      loadProjectOptions()
      loadDistributionChart()
      loadRecordChart()
      loadTrendChart()
      loadRankingData()
      loadTableData()

      // 窗口大小变化时重新渲染图表
      window.addEventListener('resize', handleResize)
    })

    onUnmounted(() => {
      // 销毁图表实例
      if (distributionChartInstance) {
        distributionChartInstance.dispose()
      }
      if (recordChartInstance) {
        recordChartInstance.dispose()
      }
      if (trendChartInstance) {
        trendChartInstance.dispose()
      }
      if (analysisChart1Instance) {
        analysisChart1Instance.dispose()
      }
      if (analysisChart2Instance) {
        analysisChart2Instance.dispose()
      }
      if (analysisChart3Instance) {
        analysisChart3Instance.dispose()
      }
      if (analysisChart4Instance) {
        analysisChart4Instance.dispose()
      }
      window.removeEventListener('resize', handleResize)
    })

    // 加载概览数据
    const loadOverviewData = async () => {
      try {
        const response = await getScoreOverview()
        if (response.code === 200) {
          Object.assign(overviewData, response.data)
        }
      } catch (error) {
        console.error('加载概览数据失败:', error)
      }
    }

    // 加载项目选项
    const loadProjectOptions = async () => {
      try {
        const response = await getProjectOverview()
        if (response.code === 200) {
          projectOptions.value = response.data.projects || []
        }
      } catch (error) {
        console.error('加载项目选项失败:', error)
      }
    }

    // 加载成绩分布图
    const loadDistributionChart = async () => {
      try {
        const projectId = filterForm.projectId
        if (!projectId) return

        const response = await getScoreDistribution(projectId)
        if (response.code === 200) {
          renderDistributionChart(response.data)
        }
      } catch (error) {
        console.error('加载成绩分布图失败:', error)
      }
    }

    // 渲染成绩分布图
    const renderDistributionChart = (data) => {
      nextTick(() => {
        if (!distributionChart.value) return

        if (distributionChartInstance) {
          distributionChartInstance.dispose()
        }

        distributionChartInstance = echarts.init(distributionChart.value)

        const chartData = data.distribution || []
        const option = distributionChartType.value === 'histogram' ? {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: chartData.map(item => item.range),
            name: '成绩区间'
          },
          yAxis: {
            type: 'value',
            name: '人数'
          },
          series: [
            {
              name: '人数',
              type: 'bar',
              data: chartData.map(item => item.count),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#83bff6' },
                  { offset: 0.5, color: '#188df0' },
                  { offset: 1, color: '#188df0' }
                ])
              }
            }
          ]
        } : {
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            name: '成绩'
          },
          yAxis: {
            type: 'category',
            data: chartData.map(item => item.range),
            name: '成绩区间'
          },
          series: [
            {
              name: '成绩分布',
              type: 'boxplot',
              data: [chartData.map(item => item.values)]
            }
          ]
        }

        distributionChartInstance.setOption(option)
      })
    }

    // 加载破纪录统计图
    const loadRecordChart = async () => {
      try {
        const response = await getRecordBreakingStats()
        if (response.code === 200) {
          renderRecordChart(response.data)
        }
      } catch (error) {
        console.error('加载破纪录统计图失败:', error)
      }
    }

    // 渲染破纪录统计图
    const renderRecordChart = (data) => {
      nextTick(() => {
        if (!recordChart.value) return

        if (recordChartInstance) {
          recordChartInstance.dispose()
        }

        recordChartInstance = echarts.init(recordChart.value)

        const chartData = data.records || []
        const option = recordChartType.value === 'time' ? {
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['破纪录次数']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: chartData.map(item => item.date)
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '破纪录次数',
              type: 'line',
              data: chartData.map(item => item.count),
              itemStyle: {
                color: '#f56c6c'
              },
              smooth: true
            }
          ]
        } : {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '项目破纪录分布',
              type: 'pie',
              radius: '50%',
              data: chartData.map(item => ({
                name: item.projectName,
                value: item.count
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }

        recordChartInstance.setOption(option)
      })
    }

    // 加载趋势图
    const loadTrendChart = async () => {
      try {
        const params = {
          projectIds: filterForm.projectId ? [filterForm.projectId] : [],
          chartType: 'line',
          timeRange: filterForm.timeRange
        }

        const response = await getScoreComparisonChart(params)
        if (response.code === 200) {
          renderTrendChart(response.data)
        }
      } catch (error) {
        console.error('加载趋势图失败:', error)
      }
    }

    // 渲染趋势图
    const renderTrendChart = (data) => {
      nextTick(() => {
        if (!trendChart.value) return

        if (trendChartInstance) {
          trendChartInstance.dispose()
        }

        trendChartInstance = echarts.init(trendChart.value)

        const chartData = data.series || []
        const option = {
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: chartData.map(item => item.name)
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: data.dates || []
          },
          yAxis: {
            type: 'value'
          },
          series: chartData.map(item => ({
            name: item.name,
            type: 'line',
            data: item.data,
            smooth: true,
            itemStyle: {
              color: item.color
            }
          }))
        }

        trendChartInstance.setOption(option)
      })
    }

    // 加载排行榜数据
    const loadRankingData = async () => {
      try {
        const projectId = filterForm.projectId
        if (!projectId && rankingType.value === 'project') return

        const params = {
          rankType: 'score',
          limit: 10
        }

        const response = projectId ?
          await getProjectRanking(projectId, params) :
          await getScoreOverview()

        if (response.code === 200) {
          rankingData.value = response.data.rankings || []
        }
      } catch (error) {
        console.error('加载排行榜数据失败:', error)
      }
    }

    // 加载表格数据
    const loadTableData = async () => {
      tableLoading.value = true
      try {
        // 模拟数据，实际应该调用API
        const mockData = [
          {
            id: 1,
            participantName: '张三',
            studentId: '2021001',
            collegeName: '计算机学院',
            className: '软件工程21-1班',
            projectName: '100米短跑',
            projectType: '个人',
            score: 10.58,
            unit: '秒',
            rank: 1,
            isRecord: true,
            isPB: true,
            recordTime: '2024-03-15 14:30:00',
            improvement: 0.12,
            originalRecord: 10.70,
            venue: '田径场',
            refereeName: '李裁判',
            weather: '晴朗'
          },
          {
            id: 2,
            participantName: '李四',
            studentId: '2021002',
            collegeName: '计算机学院',
            className: '软件工程21-2班',
            projectName: '跳远',
            projectType: '个人',
            score: 6.85,
            unit: '米',
            rank: 2,
            isRecord: false,
            isPB: true,
            recordTime: '2024-03-14 15:20:00',
            improvement: 0.15
          },
          {
            id: 3,
            participantName: '王五',
            studentId: '2021003',
            collegeName: '电子工程学院',
            className: '通信工程21-1班',
            projectName: '铅球',
            projectType: '个人',
            score: 12.45,
            unit: '米',
            rank: 1,
            isRecord: false,
            isPB: false,
            recordTime: '2024-03-13 16:10:00',
            improvement: -0.05
          }
        ]

        tableData.value = mockData
        pagination.total = mockData.length
      } catch (error) {
        console.error('加载表格数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        tableLoading.value = false
      }
    }

    // 事件处理方法
    const handleRefresh = () => {
      loadOverviewData()
      loadDistributionChart()
      loadRecordChart()
      loadTrendChart()
      loadRankingData()
      loadTableData()
      ElMessage.success('数据已刷新')
    }

    const handleProjectChange = () => {
      loadDistributionChart()
      loadTrendChart()
      loadRankingData()
      loadTableData()
    }

    const handleFilterChange = () => {
      loadTableData()
    }

    const handleTimeRangeChange = () => {
      loadTrendChart()
      loadTableData()
    }

    const handleSearch = () => {
      pagination.currentPage = 1
      loadTableData()
    }

    const handleSortChange = ({ prop, order }) => {
      sortParams.prop = prop
      sortParams.order = order
      loadTableData()
    }

    const handlePageChange = (page) => {
      pagination.currentPage = page
      loadTableData()
    }

    const handlePageSizeChange = (size) => {
      pagination.pageSize = size
      loadTableData()
    }

    const handleViewDetail = (row) => {
      // 添加历史成绩数据
      currentDetail.value = {
        ...row,
        historyScores: [
          {
            date: '2024-03-01',
            score: 10.70,
            improvement: 0,
            competition: '校运会预选赛'
          },
          {
            date: '2024-03-08',
            score: 10.65,
            improvement: 0.05,
            competition: '学院选拔赛'
          },
          {
            date: '2024-03-15',
            score: 10.58,
            improvement: 0.07,
            competition: '校运会决赛'
          }
        ]
      }
      detailDialogVisible.value = true
    }

    const handleRankingHover = () => {
      // 可以添加悬停效果，比如显示详细信息
    }

    const handleRankingLeave = () => {
      // 清除悬停效果
    }

    // 导出功能
    const handleExport = async () => {
      try {
        const params = {
          format: 'excel',
          filters: {
            projectId: filterForm.projectId,
            projectType: filterForm.projectType,
            timeRange: filterForm.timeRange,
            keyword: searchKeyword.value
          }
        }

        const response = await exportScoreStats(params)

        // 创建下载链接
        const blob = new Blob([response], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `成绩统计报表_${new Date().toLocaleDateString()}.xlsx`
        link.click()
        window.URL.revokeObjectURL(url)

        ElMessage.success('报表导出成功')
      } catch (error) {
        console.error('导出报表失败:', error)
        ElMessage.error('导出报表失败')
      }
    }

    const handleGenerateReport = () => {
      analysisDialogVisible.value = true
      nextTick(() => {
        loadAnalysisCharts()
      })
    }

    const exportTableData = () => {
      ElMessage.info('表格导出功能开发中...')
    }

    const exportDetailData = () => {
      ElMessage.info('详情导出功能开发中...')
    }

    const exportAnalysisReport = () => {
      ElMessage.info('分析报告导出功能开发中...')
    }

    // 加载分析图表
    const loadAnalysisCharts = () => {
      // 这里可以加载更详细的分析图表
      loadAnalysisChart1()
      loadAnalysisChart2()
      loadAnalysisChart3()
      loadAnalysisChart4()
    }

    const loadAnalysisChart1 = () => {
      if (!analysisChart1.value) return

      analysisChart1Instance = echarts.init(analysisChart1.value)
      const option = {
        title: {
          text: '成绩分布统计'
        },
        tooltip: {},
        xAxis: {
          data: ['0-50', '50-60', '60-70', '70-80', '80-90', '90-100']
        },
        yAxis: {},
        series: [{
          name: '人数',
          type: 'bar',
          data: [5, 20, 36, 10, 10, 20]
        }]
      }
      analysisChart1Instance.setOption(option)
    }

    const loadAnalysisChart2 = () => {
      if (!analysisChart2.value) return

      analysisChart2Instance = echarts.init(analysisChart2.value)
      const option = {
        title: {
          text: '项目对比分析'
        },
        tooltip: {},
        legend: {
          data: ['平均成绩', '最高成绩']
        },
        xAxis: {
          data: ['短跑', '跳远', '铅球', '跳高', '长跑']
        },
        yAxis: {},
        series: [
          {
            name: '平均成绩',
            type: 'bar',
            data: [12.0, 6.5, 11.5, 1.8, 25.0]
          },
          {
            name: '最高成绩',
            type: 'bar',
            data: [10.5, 7.2, 13.8, 2.1, 22.5]
          }
        ]
      }
      analysisChart2Instance.setOption(option)
    }

    const loadAnalysisChart3 = () => {
      if (!analysisChart3.value) return

      analysisChart3Instance = echarts.init(analysisChart3.value)
      const option = {
        title: {
          text: '成绩变化趋势'
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: [820, 932, 901, 934, 1290, 1330],
          type: 'line',
          smooth: true
        }]
      }
      analysisChart3Instance.setOption(option)
    }

    const loadAnalysisChart4 = () => {
      if (!analysisChart4.value) return

      analysisChart4Instance = echarts.init(analysisChart4.value)
      const option = {
        title: {
          text: '破纪录统计'
        },
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            name: '破纪录类型',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 1048, name: '校纪录' },
              { value: 735, name: '院纪录' },
              { value: 580, name: '个人最好成绩' },
              { value: 484, name: '赛会纪录' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      analysisChart4Instance.setOption(option)
    }

    // 图表类型变化处理
    const handleDistributionChartTypeChange = () => {
      loadDistributionChart()
    }

    const handleRecordChartTypeChange = () => {
      loadRecordChart()
    }

    const handleTrendMetricTypeChange = () => {
      loadTrendChart()
    }

    const handleRankingTypeChange = () => {
      loadRankingData()
    }

    // 工具方法
    const handleResize = () => {
      if (distributionChartInstance) {
        distributionChartInstance.resize()
      }
      if (recordChartInstance) {
        recordChartInstance.resize()
      }
      if (trendChartInstance) {
        trendChartInstance.resize()
      }
      if (analysisChart1Instance) {
        analysisChart1Instance.resize()
      }
      if (analysisChart2Instance) {
        analysisChart2Instance.resize()
      }
      if (analysisChart3Instance) {
        analysisChart3Instance.resize()
      }
      if (analysisChart4Instance) {
        analysisChart4Instance.resize()
      }
    }

    // 监听图表类型变化
    watch(distributionChartType, handleDistributionChartTypeChange)
    watch(recordChartType, handleRecordChartTypeChange)
    watch(trendMetricType, handleTrendMetricTypeChange)
    watch(rankingType, handleRankingTypeChange)

    return {
      // 响应式数据
      loading,
      tableLoading,
      overviewData,
      filterForm,
      projectOptions,
      searchKeyword,
      tableData,
      pagination,
      rankingData,
      detailDialogVisible,
      analysisDialogVisible,
      currentDetail,
      activeAnalysisTab,
      distributionChartType,
      recordChartType,
      trendMetricType,
      rankingType,

      // 图表引用
      distributionChart,
      recordChart,
      trendChart,
      analysisChart1,
      analysisChart2,
      analysisChart3,
      analysisChart4,

      // 方法
      handleRefresh,
      handleProjectChange,
      handleFilterChange,
      handleTimeRangeChange,
      handleSearch,
      handleSortChange,
      handlePageChange,
      handlePageSizeChange,
      handleViewDetail,
      handleRankingHover,
      handleRankingLeave,
      handleExport,
      handleGenerateReport,
      exportTableData,
      exportDetailData,
      exportAnalysisReport
    }
  }
}
</script>

<style lang="scss" scoped>
.score-statistics {
  padding: 20px;

  .breadcrumb {
    margin-bottom: 20px;
  }

  // 概览卡片样式
  .overview-cards {
    margin-bottom: 20px;

    .stat-card {
      .stat-item {
        display: flex;
        align-items: center;

        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;

          .el-icon {
            font-size: 28px;
            color: white;
          }
        }

        .stat-content {
          flex: 1;

          .stat-value {
            font-size: 28px;
            font-weight: bold;
            color: #303133;
            line-height: 1;
          }

          .stat-label {
            font-size: 14px;
            color: #909399;
            margin-top: 5px;
          }
        }
      }
    }
  }

  // 筛选卡片样式
  .filter-card {
    margin-bottom: 20px;

    .filter-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .left-actions {
        display: flex;
        gap: 10px;
      }

      .right-filters {
        display: flex;
        align-items: center;
      }
    }
  }

  // 图表行样式
  .chart-row {
    margin-bottom: 20px;

    .chart-card,
    .ranking-card {
      height: 400px;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .chart-container {
        height: 320px;
        width: 100%;
      }
    }

    .ranking-card {
      .ranking-content {
        height: 320px;
        overflow-y: auto;

        .ranking-list {
          .ranking-item {
            display: flex;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: all 0.3s;

            &:hover {
              background-color: #f5f7fa;
              transform: translateX(5px);
            }

            &.top-three {
              background-color: #f9f9f9;
            }

            .rank-number {
              width: 35px;
              height: 35px;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              font-weight: bold;
              margin-right: 12px;

              &.rank-1 {
                background-color: #ffd700;
                color: #333;
              }

              &.rank-2 {
                background-color: #c0c0c0;
                color: #333;
              }

              &.rank-3 {
                background-color: #cd7f32;
                color: #fff;
              }
            }

            .rank-info {
              flex: 1;

              .rank-name {
                font-weight: 500;
                margin-bottom: 2px;
              }

              .rank-project {
                font-size: 12px;
                color: #666;
              }
            }

            .rank-score {
              text-align: right;
              margin-right: 10px;

              .score-value {
                font-size: 18px;
                font-weight: bold;
                color: #409eff;
              }

              .score-unit {
                font-size: 12px;
                color: #999;
              }
            }

            .rank-badge {
              display: flex;
              flex-direction: column;
              gap: 2px;
            }
          }
        }
      }
    }
  }

  // 表格卡片样式
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .table-actions {
        display: flex;
        align-items: center;
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }

    .score-highlight {
      font-weight: bold;
      color: #409eff;
    }

    .improvement-positive {
      color: #67c23a;
      font-weight: bold;
    }

    .improvement-negative {
      color: #f56c6c;
      font-weight: bold;
    }
  }

  // 详情对话框样式
  .detail-content {
    .el-descriptions {
      margin-top: 20px;
    }

    .score-detail {
      font-size: 18px;
      font-weight: bold;
      color: #409eff;
    }

    .history-section {
      margin-top: 20px;

      h4 {
        margin-bottom: 10px;
        color: #303133;
      }
    }
  }

  // 分析对话框样式
  .analysis-content {
    .analysis-section {
      margin-bottom: 20px;

      h4 {
        margin-bottom: 15px;
        color: #303133;
      }

      .analysis-chart {
        height: 300px;
        width: 100%;
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .score-statistics {
    .overview-cards {
      .el-col {
        margin-bottom: 10px;
      }
    }

    .chart-row {
      .el-col {
        margin-bottom: 20px;
      }
    }
  }
}

@media (max-width: 768px) {
  .score-statistics {
    padding: 10px;

    .filter-header {
      flex-direction: column;
      gap: 15px;

      .left-actions,
      .right-filters {
        width: 100%;
        justify-content: center;
      }
    }

    .chart-card,
    .ranking-card {
      height: auto;
      min-height: 300px;
    }

    .card-header {
      flex-direction: column;
      gap: 10px;
      align-items: flex-start;
    }

    .table-card {
      .card-header {
        flex-direction: column;
        gap: 15px;
        align-items: flex-start;

        .table-actions {
          width: 100%;
          justify-content: center;
        }
      }
    }
  }
}
</style>